package controllers

import (
	"fmt"
	"strings"

	"gitee.com/small_fish_official_net/beego_frame/bash"
	"gitee.com/small_fish_official_net/beego_frame/models/data"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

type Admin struct {
	beego.Controller
}

func init() {
	beego.AddFuncMap("input", admin_func_input)
	beego.AddFuncMap("input_short", admin_func_input_short)
}

func admin_func_input(name, label, val string, fujia ...string) string {
	strs := ""
	for _, v := range fujia {
		strs = strs + v
	}
	return `<div class="layui-form-item">
	<label class="layui-form-label">` + label + `</label>
	<div class="layui-input-block">
		<input type="text" name="` + name + `" autocomplete="off" placeholder="请输入` + label + `"
			class="layui-input" ` + strs + ` value="` + val + `">
	</div>
</div>`
}
func admin_func_input_short(name, label, val string, fujia ...string) string {
	strs := ""
	for _, v := range fujia {
		strs = strs + v
	}
	return `<div class="layui-inline">
	<label class="layui-form-label">` + label + `</label>
	<div class="layui-input-block">
		<input type="text" name="` + name + `" autocomplete="off" placeholder="请输入` + label + `"
			class="layui-input" ` + strs + ` value="` + val + `">
	</div>
</div>`
}

// 设置控制器的一些基本信息
func (c *Admin) Prepare() {
	// 若开启了debug模式则无需登录可直接操作
	if ok, err := beego.AppConfig.Bool("debug"); !ok || err != nil {
		// 如果未登录则直接强制跳转到登录页面
		req_uri := strings.Split(c.Ctx.Request.RequestURI, "?")[0]
		if req_uri != "/admin/login" && req_uri != "/admin/logout" {
			if c.GetSession("user_info") == nil {
				c.Redirect("/admin/login", 302)
			}
		}
	} else {
		if c.GetSession("user_info") == nil {
			o := orm.NewOrm()
			u := data.User{}
			err := bash.UseType(o).QueryTable(u).Filter("id", 1).One(&u)
			if err != nil {
				logs.Error("获取用户信息错误")
			}
			c.SetSession("user_info", u)
		}
	}
	c.TplExt = "html"
	c.Data["NowTimes"] = bash.Date("yyyy-MM-dd")
	c.Data["NowTime"] = bash.Date("hh:mm:ss")
	c.Data["NowYear"] = bash.Date("yyyy")
	c.Data["default"] = map[string]string{
		"title":       beego.AppConfig.String("Webconfig::default_title"),
		"short_title": beego.AppConfig.String("Webconfig::short_title"),
		"copyright":   beego.AppConfig.String("Webconfig::default_copyright"),
		"icp":         beego.AppConfig.String("Webconfig::default_icp"),
		"icon_data":   beego.AppConfig.String("Webconfig::icon_data"),
	}
	if c.GetSession("user_info") != nil {
		u := c.GetSession("user_info").(data.User)
		c.Data["User"] = map[string]string{
			"id":       fmt.Sprintf("%d", u.Id),
			"username": u.UserName,
			"email":    u.Email,
			"phone":    u.Phone,
			"sex":      fmt.Sprintf("%d", u.Sex),
		}
		c.Data["list"] = map[string][]string{
			"sex": u.GetSexList(),
		}
	}
	c.Layout = "admin/admin_layout.html"
}

// 传入参数形式返回json数据
func (c *Admin) return_success(info interface{}) bool {
	c.Data["json"] = info
	return c.return_json()
}

// JSON返回数据
//
// 自动获取c.Data["json"]中的对象进行返回
func (c *Admin) return_json(msg ...string) bool {
	if len(msg) == 0 {
		c.Data["json"] = map[string]interface{}{
			"code":       0,
			"message":    "成功",
			"serve_time": bash.Date(),
			"result":     c.Data["json"],
		}
	} else if len(msg) == 1 {
		c.Data["json"] = map[string]interface{}{
			"code":       1,
			"message":    msg[0],
			"serve_time": bash.Date(),
			"result":     map[string]string{},
		}
	}
	c.ServeJSON()
	return true
}

// 读操作的数据库
func (c *Admin) get_orm() orm.Ormer {
	return bash.UseType(orm.NewOrm())
}

// 写操作的数据库
func (c *Admin) set_orm() orm.Ormer {
	return bash.UseType(orm.NewOrm(), "write")
}
